package com.inspur.edp.rule.dsl.core.function.list.getter;

import com.inspur.edp.rule.dsl.core.function.ObjectMethodNameUtil;
import com.inspur.edp.rule.dsl.core.function.list.IGetFieldValue;
import lombok.Data;

import java.lang.reflect.Method;

@Data
public class MethodGetter implements IGetFieldValue {

    private Method method;

    public MethodGetter(Class cls, String fieldName) {
        String methodName = ObjectMethodNameUtil.getGetName(fieldName);
        try {
            this.method = cls.getMethod(methodName, null);
        } catch (Throwable throwable) {
            throw new IllegalArgumentException("get field method info occur error.", throwable);
        }
    }

    @Override
    public Object getFieldValue(Object object) {
        try {
            return method.invoke(object, null);
        } catch (Throwable throwable) {
            throw new IllegalArgumentException("get field value occur error.", throwable);
        }
    }

    @Override
    public String getString(Object object) {
        return (String) this.getFieldValue(object);
    }

    @Override
    public Number getNumber(Object object) {
        return (Number) this.getFieldValue(object);
    }
}
